package com.example.app3_1;

// BookListActivity.java
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

public class BookListActivity extends AppCompatActivity {
    private EditText etBookId, etBookName;
    private Button btnAdd, btnDelete, btnUpdate, btnQuery;
    private RecyclerView recyclerView;
    private BookAdapter adapter;
    private List<Book> books = new ArrayList<>();
    private String username;
    private SharedPreferences sharedPreferences;
    private Gson gson = new Gson();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_book_list);

        // 获取用户名
        username = getIntent().getStringExtra("username");
        sharedPreferences = getSharedPreferences("BookData", MODE_PRIVATE);

        // 初始化视图
        initViews();

        // 加载书籍数据
        loadBooks();

        // 设置适配器
        adapter = new BookAdapter(books, book -> {
            // 点击列表项，填充到输入框
            etBookId.setText(book.getId());
            etBookName.setText(book.getName());
        });

        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(adapter);

        // 设置按钮点击事件
        setupButtonListeners();
    }

    private void initViews() {
        etBookId = findViewById(R.id.et_book_id);
        etBookName = findViewById(R.id.et_book_name);
        btnAdd = findViewById(R.id.btn_add);
        btnDelete = findViewById(R.id.btn_delete);
        btnUpdate = findViewById(R.id.btn_update);
        btnQuery = findViewById(R.id.btn_query);
        recyclerView = findViewById(R.id.recycler_view);
    }

    private void setupButtonListeners() {
        btnAdd.setOnClickListener(v -> addBook());
        btnDelete.setOnClickListener(v -> deleteBook());
        btnUpdate.setOnClickListener(v -> updateBook());
        btnQuery.setOnClickListener(v -> queryBooks());
    }

    private void loadBooks() {
        String booksJson = sharedPreferences.getString(username, "");
        if (!booksJson.isEmpty()) {
            Type listType = new TypeToken<List<Book>>(){}.getType();
            books = gson.fromJson(booksJson, listType);
            if (books == null) {
                books = new ArrayList<>();
            }
        }
    }

    private void saveBooks() {
        String booksJson = gson.toJson(books);
        sharedPreferences.edit().putString(username, booksJson).apply();
    }

    private void addBook() {
        String id = etBookId.getText().toString().trim();
        String name = etBookName.getText().toString().trim();

        if (id.isEmpty() || name.isEmpty()) {
            Toast.makeText(this, "书号和书名不能为空", Toast.LENGTH_SHORT).show();
            return;
        }

        // 检查书号是否已存在
        for (Book book : books) {
            if (book.getId().equals(id)) {
                Toast.makeText(this, "书号已存在", Toast.LENGTH_SHORT).show();
                return;
            }
        }

        books.add(new Book(id, name));
        saveBooks();
        adapter.updateBooks(books);
        clearInputs();
        Toast.makeText(this, "添加成功", Toast.LENGTH_SHORT).show();
    }

    private void deleteBook() {
        String id = etBookId.getText().toString().trim();

        if (id.isEmpty()) {
            Toast.makeText(this, "请输入要删除的书号", Toast.LENGTH_SHORT).show();
            return;
        }

        for (int i = 0; i < books.size(); i++) {
            if (books.get(i).getId().equals(id)) {
                books.remove(i);
                saveBooks();
                adapter.updateBooks(books);
                clearInputs();
                Toast.makeText(this, "删除成功", Toast.LENGTH_SHORT).show();
                return;
            }
        }

        Toast.makeText(this, "未找到该书号", Toast.LENGTH_SHORT).show();
    }

    private void updateBook() {
        String id = etBookId.getText().toString().trim();
        String name = etBookName.getText().toString().trim();

        if (id.isEmpty() || name.isEmpty()) {
            Toast.makeText(this, "书号和书名不能为空", Toast.LENGTH_SHORT).show();
            return;
        }

        for (Book book : books) {
            if (book.getId().equals(id)) {
                book.setName(name);
                saveBooks();
                adapter.updateBooks(books);
                clearInputs();
                Toast.makeText(this, "修改成功", Toast.LENGTH_SHORT).show();
                return;
            }
        }

        Toast.makeText(this, "未找到该书号", Toast.LENGTH_SHORT).show();
    }

    private void queryBooks() {
        String id = etBookId.getText().toString().trim();
        String name = etBookName.getText().toString().trim();

        if (id.isEmpty() && name.isEmpty()) {
            // 空查询显示全部
            adapter.updateBooks(books);
            return;
        }

        List<Book> result = new ArrayList<>();
        for (Book book : books) {
            boolean match = true;
            if (!id.isEmpty() && !book.getId().contains(id)) {
                match = false;
            }
            if (!name.isEmpty() && !book.getName().contains(name)) {
                match = false;
            }
            if (match) {
                result.add(book);
            }
        }

        adapter.updateBooks(result);
        Toast.makeText(this, "找到 " + result.size() + " 本书", Toast.LENGTH_SHORT).show();
    }

    private void clearInputs() {
        etBookId.setText("");
        etBookName.setText("");
    }
}